package com.vicene.gmail.auth.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.TypeReference;
import com.vicene.gmail.auth.feign.MemberFeignService;
import com.vicene.gmail.auth.weibo.WeiBoAuth;
import com.vicene.gmail.common.utils.HttpUtil;
import com.vicene.gmail.common.utils.R;
import com.vicene.gmail.common.vo.WeiBoLoginResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class Oauth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code , HttpServletRequest request , HttpSession session){
        System.out.println(code);
        Map<String ,String> params = new HashMap<>();
        params.put("client_id" , "3896929093");
        params.put("client_secret" , "792435451fa0b041e28d07c671021e84");
        params.put("grant_type" , "authorization_code");
        params.put("redirect_uri" , "http://auth.gmail.com/oauth2.0/weibo/success");
        params.put("code" , code);


        String result = HttpUtil.doPost("https://api.weibo.com/oauth2/access_token" ,params);
        WeiBoAuth weiBoAuth =  JSONUtil.toBean(result , WeiBoAuth.class);
        if(weiBoAuth != null && weiBoAuth.getAccess_token() != null){
            R r = memberFeignService.oauthLogin(weiBoAuth);
            if(r.getCode() == 0){
                log.info("用戶登錄成功{}:", r.getData(new TypeReference<WeiBoLoginResp>(){}).toString());
                session.setAttribute("loginUser" , r.getData(new TypeReference<WeiBoLoginResp>(){}));
            }
        }

        System.out.println(result);
        return "redirect:http://gmail.com";
    }
}
